package com.suxin.plugin.loader.load;

import com.suxin.plugin.loader.PluginResourceLoader;
import com.suxin.plugin.loader.ResourceWrapper;
import com.suxin.plugin.pf4j.BasePlugin;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ClassUtils;

/**
 * @author Tang
 * @classname PluginClassLoader
 * @description [ 插件类文件加载者 ]
 * @date 2022/7/21 22:36
 */
public class PluginClassLoader implements PluginResourceLoader {

    public static final String KEY = "PluginClassProcess";

    @Override
    public String key() {
        return KEY;
    }

    @Override
    public ResourceWrapper load(BasePlugin basePlugin) throws Exception{
        String scanPackage = basePlugin.scanPackage();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                ClassUtils.convertClassNameToResourcePath(scanPackage) + "/**/*.class";
        // 获取插件包中的类
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(
                basePlugin.getPluginWrapper().getClassLoader()
        );
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        return new ResourceWrapper(resources);
    }

    @Override
    public void unload(BasePlugin basePlugin, ResourceWrapper resourceWrapper) throws Exception {

    }
}
